//
//  constructionViewController.m
//  Runone
//
//  Created by runone01 on 16/8/30.
//  Copyright © 2016年 runone. All rights reserved.
//

#import "constructionViewController.h"
#import "RequestHelper.h"
#import "MJExtension.h"
#import "ConstructionEventDetailInfo.h"
#import "ParModel.h"
#import "TollIncidentViewController.h"
#import "ChooseLineTableViewController.h"
#import "UUDatePicker.h"
#import "TableOperation.h"
#import "PileInfo.h"
#import "UUDatePicker.h"
#import "POPDatePickViewController.h"
#import "EventDealList.h"
#import "CommonUtilityjudge.h"
#import "PromptUtil.h"
#import "CityDirectionController.h"
#import "UIView+Message.h"
#import "DateViewController.h"
#import "UITextField+ToolBar.h"
#import "SGImagePickerController.h"
#import "UIColor+ZXLazy.h"
#import "UITextView+ToolBar.h"
#import "SVProgressHUD.h"
#import "BCNetAPIClient.h"

@interface constructionViewController ()<UIPopoverPresentationControllerDelegate,UITextViewDelegate,UIAlertViewDelegate,UITextFieldDelegate>
//输入控件
@property (weak, nonatomic) IBOutlet UITextField *ConstructionTF;
@property (weak, nonatomic) IBOutlet UITextField *HeaderTF;
@property (weak, nonatomic) IBOutlet UITextField *Number;
@property (weak, nonatomic) IBOutlet UITextField *beginPir;
@property (weak, nonatomic) IBOutlet UITextField *BeginDistance;
@property (weak, nonatomic) IBOutlet UITextField *EndPir;
@property (weak, nonatomic) IBOutlet UITextField *EndDisTance;
@property (weak, nonatomic) IBOutlet UITextField *PlanBeginTime;
@property (weak, nonatomic) IBOutlet UITextField *PlanEndTime;
@property (weak, nonatomic) IBOutlet UITextField *WorkContent;
@property (weak, nonatomic) IBOutlet UITextView *DesCription;
@property (weak, nonatomic) IBOutlet UIButton *ImageBtn;
@property (weak, nonatomic) IBOutlet UIButton *VideoBtn;
@property (weak, nonatomic) IBOutlet UITextField *MoreChoose;
@property (weak, nonatomic) IBOutlet UITextField *cityDirTF;
@property (weak, nonatomic) IBOutlet UIScrollView *imageScrollView;

//类+控制器
@property(nonatomic,strong)UIAlertView *resultAlert;
@property(nonatomic,strong)DateViewController *dateVC;//时间VC
@property(nonatomic,strong)CurrentEvent *model;
@property(nonatomic,strong)PromptUtil *Prompt;
@property(nonatomic,strong)CityDirectionController *citypop;
@property(nonatomic,strong)POPDatePickViewController *popdate;
@property(nonatomic,strong)ChooseLineTableViewController *chooseLineVC;
@property(nonatomic,strong)TollIncidentViewController *vc;
@property(nonatomic,strong)EventDealList *listModel;
//辅助值
@property(nonatomic,strong)UIView *ResultView;
@property(nonatomic)NSInteger code;
@property(nonatomic,strong)UIAlertView *alert;
@property(nonatomic,strong)UIImage *img;
@property(nonatomic,strong)UIImage *loadImage;
@property(nonatomic,strong)UIImageView *iv;

@property(nonatomic)int beginPirNo;
@property(nonatomic)int endPirNo;
@property(nonatomic)int beginPirDistance;
@property(nonatomic)int endPirDistance;
@end

@implementation constructionViewController

-(void)viewWillAppear:(BOOL)animated
{
    [self.tabBarController.tabBar setHidden:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title=@"施工事件上报";
    UILabel *label=[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 150, 30)];
    label.text=@"施工事件上报";
    label.textAlignment=NSTextAlignmentCenter;
    label.textColor=[UIColor whiteColor];
    self.navigationItem.titleView=label;
    [self TFConfirem];
    [self datePick];
    [self chooseLine];
    

    
    //线路选择
    [self dropBtn];
    //计划开始时间
    [self planBeginTimeTF];
    //计划结束时间
    [self planEndTimeTF];
    //上报
    [self Commit];
    [self AddchooseCityDirectorBtn];
    _PlanBeginTime.delegate=self;
    _PlanEndTime.delegate=self;
    //    _dateVC=[[DateViewController alloc] init];
    _Prompt=[[PromptUtil alloc] init];
    
    _listModel=[[EventDealList alloc] init];
    _citypop=[[CityDirectionController alloc] init];
    _DesCription.delegate=self;
    _cityDirTF.delegate=self;
    _MoreChoose.delegate=self;
}


-(void)Commit
{
    self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc] initWithTitle:@"提交" style:UIBarButtonItemStylePlain target:self action:@selector(Report)];
}

-(void)TFConfirem
{
    [_ConstructionTF setTextFieldInputAccessoryView:_ConstructionTF frame:CGRectMake(0, 0, self.view.frame.size.width, 40)];
    _ConstructionTF.clearButtonMode=UITextFieldViewModeAlways;
    
    [_HeaderTF setTextFieldInputAccessoryView:_HeaderTF frame:CGRectMake(0, 0, self.view.frame.size.width, 40)];
    _HeaderTF.clearButtonMode=UITextFieldViewModeAlways;
    
    [_Number setTextFieldInputAccessoryView:_Number frame:CGRectMake(0, 0, self.view.frame.size.width, 40)];
    _Number.clearButtonMode=UITextFieldViewModeAlways;
    
    [_beginPir setTextFieldInputAccessoryView:_beginPir frame:CGRectMake(0, 0, self.view.frame.size.width, 40)];
    
    [_BeginDistance setTextFieldInputAccessoryView:_BeginDistance frame:CGRectMake(0, 0, self.view.frame.size.width, 40)];
    
    [_EndPir setTextFieldInputAccessoryView:_EndPir frame:CGRectMake(0, 0, self.view.frame.size.width, 40)];
    
    [_EndDisTance setTextFieldInputAccessoryView:_EndDisTance frame:CGRectMake(0, 0, self.view.frame.size.width, 40)];
    
    [_WorkContent setTextFieldInputAccessoryView:_WorkContent frame:CGRectMake(0, 0, self.view.frame.size.width, 40)];
    _WorkContent.clearButtonMode=UITextFieldViewModeAlways;
    
    [_DesCription setTextFieldInputAccessoryView:_DesCription frame:CGRectMake(0, 0, self.view.frame.size.width, 40)];
    
}

-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    return NO;
}


-(void)AddchooseCityDirectorBtn
{
    UIButton *btn=[[UIButton alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
    [btn setBackgroundImage:[UIImage imageNamed:@"xiala"] forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(popCityDir:) forControlEvents:UIControlEventTouchUpInside];
    
    self.cityDirTF.rightView=btn;
    self.cityDirTF.rightViewMode=UITextFieldViewModeAlways;
}


-(void)popCityDir:(UIButton *)btn {
    _citypop.modalPresentationStyle=UIModalPresentationPopover;
    __weak typeof(self) weakSelf=self;
//    _citypop.LineBlock=^(NSInteger index){
//        if (index==0) {
//            NSLog(@"%ld",(long)index);
//            weakSelf.cityDirTF.text=@"广州方向";
//        }
//        if (index==1) {
//            NSLog(@"%ld",(long)index);
//            weakSelf.cityDirTF.text=@"湖南方向";
//            
//        } if (index==2) {
//            NSLog(@"%ld",(long)index);
//            weakSelf.cityDirTF.text=@"双向";
//        }
//    };
    _citypop.popoverPresentationController.sourceView=btn;
    _citypop.popoverPresentationController.delegate=self;
    _citypop.popoverPresentationController.sourceRect=CGRectMake(-70, 0, 100, 210);
    _citypop.popoverPresentationController.permittedArrowDirections=NO;
    [self presentViewController:_citypop animated:YES completion:nil];
}


-(void)datePick
{
    _dateVC=[[DateViewController alloc] init];
    _dateVC.modalPresentationStyle=UIModalPresentationPopover;
    _dateVC.popoverPresentationController.sourceView=self.view;
    _dateVC.popoverPresentationController.sourceRect=CGRectMake(self.view.center.x-56, self.view.center.y, 0, 0);
    _dateVC.popoverPresentationController.permittedArrowDirections=NO;
    _dateVC.popoverPresentationController.delegate=self;
    
    
}


-(void)textViewDidBeginEditing:(UITextView *)textView
{
    if ([_DesCription.text isEqualToString:@"请输入事件描述："]) {
        
        _DesCription.text=@"";
        _DesCription.textColor=[UIColor blackColor];
    }
}


- (void)textViewDidEndEditing:(UITextView *)textView {
    if (textView.text.length<1) {
        textView.text = @"请输入事件描述：";
        textView.textColor=[UIColor grayColor];
    }
}


-(void)chooseLine
{
//    _chooseLineVC=[[ChooseLineTableViewController alloc] init];
//    _chooseLineVC.modalPresentationStyle=UIModalPresentationPopover;
//    __weak typeof(self) weakSelf=self;
//    _chooseLineVC.LineBlock=^(NSInteger index){
//        if (index==0) {
//            weakSelf.MoreChoose.text=@"主线";
//        }
//        if (index==1) {
//            weakSelf.MoreChoose.text=@"匝道";
//        } if (index==2) {
//            weakSelf.MoreChoose.text=@"北连接线";
//        }
//        if (index==3) {
//            weakSelf.MoreChoose.text=@"南连接线";
//        }
//    };
}


-(UIModalPresentationStyle)adaptivePresentationStyleForPresentationController:(UIPresentationController *)controller
{
    return UIModalPresentationNone;
}


-(void)dropBtn
{
    
    UIButton *btn=[[UIButton alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
    [btn setBackgroundImage:[UIImage imageNamed:@"xiala"] forState:UIControlStateNormal];
    self.MoreChoose.rightView=btn;
    [btn addTarget:self action:@selector(drop:) forControlEvents:UIControlEventTouchUpInside];
    _MoreChoose.rightViewMode=UITextFieldViewModeAlways;
    
}


-(void)drop:(UIButton *)btn
{
    _chooseLineVC.popoverPresentationController.sourceView=btn;
    _chooseLineVC.popoverPresentationController.delegate=self;
    _chooseLineVC.popoverPresentationController.sourceRect=CGRectMake(-15,130,0, 0);
    _chooseLineVC.popoverPresentationController.permittedArrowDirections=NO;
    [self presentViewController:_chooseLineVC animated:YES completion:nil];
    
}


#pragma mark - 开始时间选择器
-(void)planBeginTimeTF
{
    UIButton *btn=[[UIButton alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
    [btn setBackgroundImage:[UIImage imageNamed:@"rili"] forState:UIControlStateNormal];
    self.PlanBeginTime.rightView=btn;
    [btn addTarget:self action:@selector(PlanBeginTimeMethod) forControlEvents:UIControlEventTouchUpInside];
    _PlanBeginTime.rightViewMode=UITextFieldViewModeAlways;
}

-(void)PlanBeginTimeMethod
{
    __weak typeof(self) weakSelf=self;
    [self datePick];
    _dateVC.dateBlock=^(NSString *str){
        weakSelf.PlanBeginTime.text=str;
    };
    
    [self presentViewController:_dateVC animated:YES completion:nil];
}

#pragma mark - 结束时间选择器
-(void)planEndTimeTF
{
    UIButton *btn=[[UIButton alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
    [btn setBackgroundImage:[UIImage imageNamed:@"rili"] forState:UIControlStateNormal];
    self.PlanEndTime.rightView=btn;
    [btn addTarget:self action:@selector(PlanEndTimeMethod) forControlEvents:UIControlEventTouchUpInside];
    _PlanEndTime.rightViewMode=UITextFieldViewModeAlways;
}

-(void)PlanEndTimeMethod
{
    __weak typeof(self) weakSelf=self;
    [self datePick];
    _dateVC.dateBlock=^(NSString *str){
        weakSelf.PlanEndTime.text=str;
    };
    
    [self presentViewController:_dateVC animated:YES completion:nil];
}

-(void)request
{
    RequestHelper *requestHelper=[[RequestHelper alloc] init];
    RequestGinsengModel *getCurrentEventModel=[[RequestGinsengModel alloc] init];
    getCurrentEventModel.URL=GetEventDataURL;
    getCurrentEventModel.DataValue = [self dataValueJson];
    getCurrentEventModel.UpdatedTime=@"2012-01-12 12:00:00";
    getCurrentEventModel.SystemCode=@"GuangleHighway";
    getCurrentEventModel.MethodName=@"ReportConstructionEventDetailInfo";
    
    requestHelper.block=^(RequestOutginseng *requestOutginseng,id dataValueModel){
        
        self.code=[requestOutginseng.Code integerValue];
        if (_code==001)
        {
            [SVProgressHUD showSuccessWithStatus:@"上报成功"];
            [self.navigationController popViewControllerAnimated:YES];
           // [self resultMessage:@"上报成功"];
        }
        else
        {
            [SVProgressHUD showSuccessWithStatus:@"上报失败"];
//            [_Prompt alert:@"其他问题，请稍后再试"];
            return;
        }
    };
    if (!_loadImage) {
        [requestHelper RequestGinsengModel:getCurrentEventModel andPushController:self];
    }
    else
    {
        [self requestTestUpdateImage:getCurrentEventModel Image:_loadImage];
    }
    
    // [requestHelper RequestGinsengModel:getCurrentEventModel];
}

-(void)requestTestUpdateImage:(RequestGinsengModel *)RequestGinseng Image:(UIImage *)LoadImage {
    [SVProgressHUD showWithStatus:@"正在上传图片,请稍后......"];
    
    UIImage *image = LoadImage;
    
    NSDictionary *dic=[[NSDictionary alloc] init];
    dic=@{@"methodName":RequestGinseng.MethodName,@"updatedtime":RequestGinseng.UpdatedTime,@"systemcode":DefaultSystemCode,@"DataValue":RequestGinseng.DataValue};
    
    [BCNetAPIClient  uploadImage:GetEventDataURL andParameters:dic andImage:image progress:^(NSProgress *progress) {
        
    }success:^(id responseObject)
     {
         [SVProgressHUD showSuccessWithStatus:@"上报成功"];
         [self.navigationController popViewControllerAnimated:YES];
     }
                         failure:^(NSError *failure) {
                             [SVProgressHUD showSuccessWithStatus:@"上报失败"];
                             NSLog(@"%@",failure);
                             return ;
                             
                         }];
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex==0) {
        NSLog(@"0");
    }
    else
    {
        [self.navigationController popViewControllerAnimated:YES];
    }
}


-(NSString *)dataValueJson
{
    ConstructionEventDetailInfo *info=[[ConstructionEventDetailInfo alloc] init];
    info.Content=self.WorkContent.text;
    info.EventBaseInfo=[[EventBaseInfo alloc] init];
    
    NSArray *arr=[[TableOperation shareInstance]  getePirNoTableOfRow:[@"K" stringByAppendingString:self.beginPir.text]];
    for (PileInfo *pir in arr) {
        NSLog(@"%f,%f",pir.Latitude,pir.Longitude);
        info.EventBaseInfo.Latitude=pir.Latitude;
        info.EventBaseInfo.Longitude=pir.Longitude;
    }
    
    info.Department=self.ConstructionTF.text;
    info.Header=self.HeaderTF.text;
    info.Telephone=_Number.text;
    
    NSString *k=@"K";
    info.EventBaseInfo.BeginPile = [k stringByAppendingString:self.beginPir.text];
    info.EventBaseInfo.BeginPileDistance = [self.BeginDistance.text integerValue];
    info.EventBaseInfo.EndPile           = [k stringByAppendingString:self.EndPir.text];
    info.EventBaseInfo.EndPileDistance   = [self.EndDisTance.text integerValue];
    info.EventBaseInfo.IncidentSource    = @"2";
    
    if ([self.MoreChoose.text isEqualToString:@"主线"]) {
        info.EventBaseInfo.RoadUID=@"8dd13d88-cb02-4471-876b-1dfe39419ee6";
    }
    if ([self.MoreChoose.text isEqualToString:@"北连接线"]) {
        info.EventBaseInfo.RoadUID=@"002";
    }
    if ([self.MoreChoose.text isEqualToString:@"南连接线"]) {
        info.EventBaseInfo.RoadUID=@"003";
    }
    if ([self.MoreChoose.text isEqualToString:@"匝道"]) {
        info.EventBaseInfo.RoadUID=@"004";
    }
    info.EventBaseInfo.OccurTime=self.PlanBeginTime.text;
    info.EventBaseInfo.EndTime=self.PlanEndTime.text;
    info.EventBaseInfo.IncidentDetail = _DesCription.text;
    info.EventBaseInfo.IncidentType=@"3";
    
    info.EventBaseInfo.IncidentDetail=self.DesCription.text;
    _listModel.DealDetail=self.DesCription.text;
    
    info.EventDealList =@[_listModel];
    
    NSMutableDictionary *dic=info.mj_keyValues;
    NSString *json = [dic mj_JSONString];
    NSLog(@"%@",json);
    
    ParModel *model=[[ParModel alloc] init];
    model.key=@"ConstructionEventDetailInfo";
    model.value=json;
    
    NSMutableDictionary *ModelDic=model.mj_keyValues;
    NSString *dataValue = [ModelDic mj_JSONString];
    NSString *str=@"[";
    NSString *temp=[str stringByAppendingString:dataValue];
    NSString *str1=@"]";
    NSString *JsonString=[temp stringByAppendingString:str1];
    
    return JsonString;
}

- (void)Report {
    
    if (stringIsEmpty(_ConstructionTF.text)) {
        [_Prompt alert:@"施工单位不能为空"];
        return;
    }
    if (stringIsEmpty(_HeaderTF.text)) {
        [_Prompt alert:@"现场负责人不能为空"];
        return;
    }
    if (stringIsEmpty(_Number.text)) {
        [_Prompt alert:@"联系电话不能为空"];
        return;
    }
    if (stringIsEmpty(_beginPir.text)) {
        [_Prompt alert:@"开始桩号不能为空"];
        return;
    }
    if (stringIsEmpty(_BeginDistance.text)) {
        [_Prompt alert:@"开始桩距离不能为空"];
        return;
    }
    if (stringIsEmpty(_EndPir.text)) {
        [_Prompt alert:@"结束桩距离不能为空"];
        return;
    }
    if (stringIsEmpty(_EndDisTance.text)) {
        [_Prompt alert:@"结束桩距离不能为空"];
        return;
    }
    if (stringIsEmpty(_MoreChoose.text)) {
        [_Prompt alert:@"请选择线路"];
        return;
    }
    if (stringIsEmpty(_PlanBeginTime.text)) {
        [_Prompt alert:@"请选择开始时间"];
        return;
    }
    if (stringIsEmpty(_PlanEndTime.text)) {
        [_Prompt alert:@"请选择结束时间"];
        return;
    }
    if (stringIsEmpty(_WorkContent.text)) {
        [_Prompt alert:@"工作内容不能为空"];
        return;
    }
    if (stringIsEmpty(_DesCription.text)) {
        [_Prompt alert:@"事件描述不能为空"];
        return;
    }
    if ([_DesCription.text isEqualToString:@"请输入事件描述："])
    {
        [_Prompt alert:@"请输入事件描述"];
        return;
    }
    int timeCompare=[_PlanBeginTime.text compare:_PlanEndTime.text];
    if (timeCompare==0) {
        [_Prompt alert:@"开始时间不能等于结束时间"];
        return ;
    }
    if (timeCompare>0) {
        [_Prompt alert:@"开始时间不能大于结束时间"];
        return;
    }
    if ([self isNumber:_beginPir.text]) {
        [_Prompt alert:@"请输入整形数字开始桩号"];
        return;
    }
    else
    {
        _beginPirNo=[_beginPir.text intValue];
    }
    if ([self isNumber:_EndPir.text]) {
        [_Prompt alert:@"请输入整形数字结束桩号"];
        return;
    }
    else
    {
        _endPirNo=[_EndPir.text intValue];
        
    }
    if ([self isNumber:_BeginDistance.text]) {
        [_Prompt alert:@"请输入整形数字开始桩距离"];
        return;
    }
    else
    {
        _beginPirDistance=[_BeginDistance.text intValue];
        
    }
    if ([self isNumber:_EndDisTance.text]) {
        [_Prompt alert:@"请输入整形数字结束桩距离"];
        return;
    }
    else
    {
        _endPirDistance=[_EndDisTance.text intValue];
        
    }
    if (_beginPirNo>_endPirNo) {
        [_Prompt alert:@"起始桩号不能大于结束桩号"];
        return;
    }
    if (_beginPirNo==_endPirNo) {
        if (_beginPirDistance>_endPirDistance) {
            [_Prompt alert:@"开始装桩距离不能大于结束桩距离"];
            return;
        }
    }
    if (_beginPirDistance>=999) {
        [_Prompt alert:@"开始桩距离不能大于999"];
        return;
    }
    if (_endPirDistance>=999) {
        [_Prompt alert:@"结束桩距离不能大于999"];
        return;
    }
    if (!validatePhone(_Number.text)) {
        [_Prompt alert:@"请输入有效的电话号码"];
        return;
    }
    
    [self request];
    
}

- (BOOL) isNumber:(NSString *)text;
{
    NSString *regex =@"[0-9]*";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
    if (![pred evaluateWithObject:text]) {
        NSLog(@"不是");
        return YES;
    }
    NSLog(@"是");
    return NO;
}

//提示
-(void)resultMessage:(NSString *)result
{
    _resultAlert=[[UIAlertView alloc] initWithTitle:@"提示" message:result delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [_resultAlert show];
}

- (IBAction)UploadImage:(UIButton *)sender {
    if (_imageScrollView) {
        for (UIView *subView in _imageScrollView.subviews) {
            [subView removeFromSuperview];
        }
    }
    
    SGImagePickerController *picker = [[SGImagePickerController alloc] initWithRootViewController:self];
    
    //返回选择的缩略图
    [picker setDidFinishSelectThumbnails:^(NSArray *thumbnails) {
        for (int i=0;i<thumbnails.count;i++) {
            _img=thumbnails[i];
            //_loadImage=thumbnails[i];
            _iv=[[UIImageView alloc] initWithFrame:CGRectMake(2+(125+2)*i, 0, 125, 125)];
            _iv.image=_img;
            [_imageScrollView addSubview:_iv];
        }
        _imageScrollView.contentSize=CGSizeMake(thumbnails.count*125, 125);
        NSLog(@"缩略图%@",thumbnails);
        
    }];
    
    //返回选中的原图
    [picker setDidFinishSelectImages:^(NSArray *images) {
        for (int i=0;i<images.count;i++ ) {
               _loadImage=images[i];
        }
        NSLog(@"原图%@,%lu",images,(unsigned long)images.count);
    }];
    [self presentViewController:picker animated:YES completion:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
